import { useIntersectionObserver } from '@vueuse/core';

const DISTANCE = 100;
const DURATION = 1000;

const animationMap = new WeakMap();

export default {
    install(app) {
        app.directive('slide-in', {
            mounted(el) {
                // 检测进入视口
                const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
                    if (!isIntersecting) {
                        // 创建动画并存储
                        const animation = el.animate([
                            { transform: `translateY(${DISTANCE}px)`, opacity: 0.5 },
                            { transform: 'translateY(0)', opacity: 1 },
                        ], { duration: DURATION, easing: 'ease-in-out' });
                        animation.pause();
                        animationMap.set(el, animation);
                    } else {
                        // 播放并取消监听
                        if (animationMap.has(el)) animationMap.get(el).play();
                        stop();
                    }
                });
            }
        });
    },
}